/* z_combine_results.do *********************************************************

	Combine all the estimation output into one large .csv to be pasted into
	our final Excel deck

*******************************************************************************/
set more off

*Now combining results
clear all

* Sections
	* Joint-F test results need to be compiled first before main resutls can all
	* be compiled together
local joint_f_outcomes		1
local joint_f_subgroups		1
local main_results				1

if `joint_f_outcomes' == 1 {

	local joint_f_files "joint_f_outcome"
	foreach analysis of local joint_f_files {

		* Combine results
		clear
		local myfilelist: dir "$results/tables/`analysis'/" files "*.csv"

		foreach f of local myfilelist {
			clear
			import delimited using "$results/tables/`analysis'/`f'", delimiter(",=") varnames(1) stripquotes(yes)

			gen row_id = _n
			destring, replace
			save "$results/tables/intermediates/`f'.dta", replace
		}

		clear
		set obs 17
		gen row_id = _n
		foreach f of local myfilelist {
			display in red "merged: `f'"
			merge 1:1 row_id using "$results/tables/intermediates/`f'.dta", nogen
		}

		drop row_id v1 v3
		rename v2 v1

		* Save Excel file
		outsheet using "$results/tables/`analysis'.csv", replace comma
	}
}

if `joint_f_subgroups' == 1 {
	local joint_f_files "joint_f_subgroup"

	foreach analysis of local joint_f_files {

		* Combine results
		clear
		local myfilelist: dir "$results/tables/`analysis'/" files "*.csv"

		foreach f of local myfilelist {
			clear
			import delimited using "$results/tables/`analysis'/`f'", varnames(1) delimiter(",=") stripquotes(yes)
			local f_new = subinstr("`f'", ".csv", "", .)
			display in red "f_new: `f_new'"
			rename y `f_new'
			destring, replace
			save "$results/tables/intermediates/`f'.dta", replace
		}

		clear all
		set obs 1
		foreach f of local myfilelist {
			display in red "appended: `f'"
			append using "$results/tables/intermediates/`f'.dta"
		}

		drop v1 v3
		rename v2 v1

		* Save Excel file
		outsheet using "$results/tables/`analysis'.csv", replace comma
	}
}

if `main_results' == 1 {
	clear
	local myfilelist: dir "$results/tables/" files "*.csv"

	foreach f of local myfilelist {
		preserve
		clear
		insheet using "$results/tables/`f'", names
		gen spec = "`f'"
		order spec
		save "$results/tables/intermediates/`f'.dta", replace
		restore
		append using "$results/tables/intermediates/`f'.dta", force

	}

	export excel "$results/tables/final_deck_results.xlsx", sheet("raw") sheetmodify firstrow(variables)
}
